<template>
  <div
      class="diy_edit merchant_users_edits page_merchant_users"
      id="merchant_users_edit"
  >
    <el-form
        :model="form"
        ref="ruleFormRef" 
		:rules="rules"
        label-width="auto"
        class="edit_merchant_users_form"
        size="large"
    >
      <el-row class="row_e">
        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="头像" prop="avatar">
            <el-upload class="avatar-uploader" drag accept="image/jpeg, image/png, image/jpg"
                action="" :http-request="uploadUserAvatar" :show-file-list="false">
              <img v-if="form_user.avatar" :src="$fullUrl($banseUrl, form_user.avatar)" class="avatar"/>
              <el-icon v-else><Plus/></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="账号" prop="username">
            <span v-if="obj_user.username">{{ obj_user.username }}</span>
            <el-input v-else v-model="form_user.username" placeholder="请输入用户名" autocomplete="new-password"></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form_user.nickname" placeholder="请输入昵称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item v-if="!obj_user.password" label="密码" prop="password">
            <span v-if="obj_user.password">{{ obj_user.password }}</span>
            <el-input v-else type="password" v-model="form_user.password" placeholder="请输入密码" show-password autocomplete="new-password"></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="邮箱" prop="email">
            <el-input type="email" v-model="form_user.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="状态" prop="state">
            <el-select v-model="form_user.state" placeholder="请选择">
              <el-option v-for="group in list_user_state" :key="group.value" :label="group.name" :value="group.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
	          <el-col v-if="$check_field('ger','merchant_name','/merchant_users/view') || $check_field('add','merchant_name','/merchant_users/view') || $check_field('set','merchant_name','/merchant_users/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="商家名称" prop="merchant_name">
                      <el-input id="merchant_name" v-model="form['merchant_name']" placeholder="请输入商家名称"
                      v-if="(form['merchant_users_id'] && $check_field('set','merchant_name','/merchant_users/view')) || (!form['merchant_users_id'] && $check_field('add','merchant_name','/merchant_users/view'))" :disabled="disabledObj['merchant_name_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','merchant_name','/merchant_users/view')">{{form['merchant_name']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','person_in_charge','/merchant_users/view') || $check_field('add','person_in_charge','/merchant_users/view') || $check_field('set','person_in_charge','/merchant_users/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="负责人" prop="person_in_charge">
                      <el-input id="person_in_charge" v-model="form['person_in_charge']" placeholder="请输入负责人"
                      v-if="(form['merchant_users_id'] && $check_field('set','person_in_charge','/merchant_users/view')) || (!form['merchant_users_id'] && $check_field('add','person_in_charge','/merchant_users/view'))" :disabled="disabledObj['person_in_charge_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','person_in_charge','/merchant_users/view')">{{form['person_in_charge']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','store_phone','/merchant_users/view') || $check_field('add','store_phone','/merchant_users/view') || $check_field('set','store_phone','/merchant_users/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="店铺电话" prop="store_phone">
                <el-input id="store_phone" v-model="form['store_phone']" placeholder="请输入店铺电话" type="tel"
                      v-if="(form['merchant_users_id'] && $check_field('set','store_phone','/merchant_users/view')) || (!form['merchant_users_id'] && $check_field('add','store_phone','/merchant_users/view'))">
            </el-input>
            <div v-else-if="$check_field('ger','store_phone','/merchant_users/view')">{{form['store_phone']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','store_address','/merchant_users/view') || $check_field('add','store_address','/merchant_users/view') || $check_field('set','store_address','/merchant_users/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="店铺地址" prop="store_address">
                      <el-input id="store_address" v-model="form['store_address']" placeholder="请输入店铺地址"
                      v-if="(form['merchant_users_id'] && $check_field('set','store_address','/merchant_users/view')) || (!form['merchant_users_id'] && $check_field('add','store_address','/merchant_users/view'))" :disabled="disabledObj['store_address_isDisabled']"></el-input>
            <div v-else-if="$check_field('ger','store_address','/merchant_users/view')">{{form['store_address']}}</div>
                    </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','registered_capital','/merchant_users/view') || $check_field('add','registered_capital','/merchant_users/view') || $check_field('set','registered_capital','/merchant_users/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="注册资金" prop="registered_capital">
                <el-input-number id="registered_capital" v-model.number="form['registered_capital']"
                             v-if="(form['merchant_users_id'] && $check_field('set','registered_capital','/merchant_users/view')) || (!form['merchant_users_id'] && $check_field('add','registered_capital','/merchant_users/view'))" :disabled="disabledObj['registered_capital_isDisabled']"></el-input-number>
            <div v-else-if="$check_field('ger','registered_capital','/merchant_users/view')">{{form['registered_capital']}}</div>
              </el-form-item>
        </el-col>
            <el-col v-if="$check_field('ger','number_of_employees','/merchant_users/view') || $check_field('add','number_of_employees','/merchant_users/view') || $check_field('set','number_of_employees','/merchant_users/view')" :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
    <el-form-item label="公司人数" prop="number_of_employees">
                <el-input-number id="number_of_employees" v-model.number="form['number_of_employees']"
                             v-if="(form['merchant_users_id'] && $check_field('set','number_of_employees','/merchant_users/view')) || (!form['merchant_users_id'] && $check_field('add','number_of_employees','/merchant_users/view'))" :disabled="disabledObj['number_of_employees_isDisabled']"></el-input-number>
            <div v-else-if="$check_field('ger','number_of_employees','/merchant_users/view')">{{form['number_of_employees']}}</div>
              </el-form-item>
        </el-col>
          <el-col :xs="24" :sm="24" :lg="24" class="el_form_item_warp">
          <el-form-item label="审核状态" prop="examine_state">
            <el-select id="examine_state" v-model="form['examine_state']"
                       v-if="(form['examine_state'] && $check_option('/merchant_users/table','examine')) || (!form['examine_state'] && $check_option('/merchant_users/table','examine'))">
              <el-option key="未审核" label="未审核" value="未审核"></el-option>
              <el-option key="已通过" label="已通过" value="已通过"></el-option>
              <el-option key="未通过" label="未通过" value="未通过"></el-option>
            </el-select>
            <div v-else>{{form["examine_state"]}}</div>
          </el-form-item>
        </el-col>

          </el-row>
      <div v-if="$check_action('/merchant_users/view','set') || $check_action('/merchant_users/view','add') || $check_option('/merchant_users/table','examine')" class="footer">
        <el-button type="primary" @click="onSubmit" size="large">提交</el-button>
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
      <div v-else class="footer">
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
  import {ElMessage} from "element-plus";
  import {ref, onMounted} from "vue";
  import { $post, $get } from "@/api/Api.js";
  import storageHelper from "@/libs/StorageHelper";
  import {useStore} from "vuex";
  import { useRouter, useRoute } from "vue-router";
  import {
          $check_field,
          $fullUrl,
          $banseUrl,
          $check_action,
          $getUrlParams,
          filterSensitiveWords,
          $get_stamp,
          $get_rand,
          $toTime,
          $push
  } from "@/utils/utils.js";

  let router = useRouter();
  let route = useRoute();
  let store = useStore();
  let token = storageHelper.getToken() || null;
  let UserInfo = storageHelper.getUserInfo();
  let user_id = storageHelper.getUserInfo().user_id;
  let user_group = storageHelper.getUserInfo().user_group;
  let merchant_users_id = $getUrlParams().merchant_users_id;
  let url_add = ref("/api/merchant_users/add");
  let url_set = ref("/api/merchant_users/set");
  let field = ref("merchant_users_id")
  let url_get_obj = ref("/api/merchant_users/get_obj");
  let url_upload = ref("/api/merchant_users/upload");
  let ruleFormRef = ref(null);
  
  let rules = ref({
						  });

  let disabledObj = ref({
      "merchant_name_isDisabled": false,
        "person_in_charge_isDisabled": false,
        "store_phone_isDisabled": false,
        "store_address_isDisabled": false,
        "registered_capital_isDisabled": false,
        "number_of_employees_isDisabled": false,
    });
    let form_user = ref({
        user_id: 0,
        username: "",
        nickname: "",
        password: "",
        avatar: "",
        email: "",
        state: 1,
			user_group: "商家用户",
    });
    let obj_user = ref({
      user_id: user_id,
      username: "",
      nickname: "",
      password: "",
      avatar: "",
      email: "",
      user_group: "商家用户",
      state: 1,
	    });
        let is_password = ref(true);
    let group_table = ref("merchant_users");
    // 账号状态
    let list_user_state = ref([
      {
        value: 1,
        name: "可用",
      },
      {
        value: 2,
        name: "异常",
      },
      {
        value: 3,
        name: "已冻结",
      },
      {
        value: 4,
        name: "已注销",
      },
    ]);
  let form = ref({
    "merchant_name":  '', // 商家名称
      "person_in_charge":  '', // 负责人
      "store_phone":  '', // 店铺电话
      "store_address":  '', // 店铺地址
      "registered_capital":  0, // 注册资金
      "number_of_employees":  0, // 公司人数
      "examine_state": "未审核",
    "merchant_users_id": 0, // ID
  });
  
    
    
    
    
    
                                                                                                                              // 上传文件
    let uploadUserAvatar = (param) => {
      uploadUserFile(param.file, "avatar");
    };
    /**
     * 上传头像
     * @param {Object} file 文件对象
     * @param {key} 保存键名
     */
    const uploadUserFile = (file, key = "img") => {
      console.log(file);
      var formobj = new FormData(); // FormData 对象
      formobj.append("file", file); // 文件对象
            $upload(url_upload.value, formobj, function (json) {
        if (json.result) {
          form_user.value[key] = json.result.url;
        } else {
          ElMessage.error("上传失败！");
        }
      });
    };
        /**
    * 上传封面图
    * @param {Object} file 文件对象
    * @param {key} 保存键名
    */
    const uploadFile = (file, key = "img") => {
        var formobj = new FormData(); // FormData 对象
        formobj.append("file", file); // 文件对象
              $upload(url_upload.value, formobj, function (json) {
          if (json.result) {
            form.value[key] = json.result.url;
          } else {
            ElMessage.error("上传失败！");
          }
        });
    };
    /**
     * 上传文件
     * @param {String} url 请求地址
     * @param {Object} body 请求参数
     * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
     * @return {Object} 返回请求结果
     */
    let $upload = async (url, body, func) => {
      url = url.replace("~/", $banseUrl);

      if (func) {
        // 如果回调函数存在, 则采用异步
              $post(url, body, {
          headers: {
            "x-auth-token": token,
            "Content-Type": "multipart/form-data",
          },
        })
            .then((res) => {
              func(res);
            })
            .catch((res) => {
              func(res);
            });
      } else {
        // 否则采用同步
        var res = await $post(url, body, {
          headers: {
            "x-auth-token": token,
            "Content-Type": "multipart/form-data",
          },
        });
        return res;
      }
    };
  //提交前验证事件
  let submit_check = () => {
                        let store_phone_phone_regular = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if(param.store_phone && !store_phone_phone_regular.test(param.store_phone)){
      return "手机号格式错误"
    }
                                };
  // 点击取消
  let cancel = () => {
    router.go(-1);
  };
    // 点击提交
    let onSubmit = async () => {
    let query_user_id = route.query.user_id
    let msg = await submit_check_user(form_user.value);
    console.log(msg);
    if (msg !== null) {
      ElMessage.error(msg);
      return;
    }
      let valid = await ruleFormRef.value.validate();
      if (valid) {
        let {
          username,
          nickname,
          avatar,
          state,
          vip_discount,
		        } = form_user.value;
        let param = {
          username,
          nickname,
          avatar,
          user_group: obj_user.value.user_group,
          state,
		        };
        if (query_user_id) {
          // 编辑
          param["user_id"] = query_user_id;
          $post("/api/user/set?user_id=" + query_user_id, form_user.value).then((res) => {
            if (res.result) {
                $get("/api/user/get_obj", param).then((list) => {
                if (list.result && list.result.obj) {
                    $post(url_set.value+"?merchant_users_id=" + form.value["merchant_users_id"], form.value).then((res2) => {
                    if (res2.result) {
					  storageHelper.setUserInfo(form_user.value)
                      ruleFormRef.value.resetFields();
                      router.push("./table");
                      ElMessage.success("修改成功！");
                    }
                  });
                }
              });
            } else if (res.error) {
              ElMessage.error(res.error.message);
            }
          });
        } else {
            // 新增
            $post("/api/user/add", form_user.value).then((res) => {
            if (res.result) {
                $get("/api/user/get_obj", param).then((list) => {
                if (list.result && list.result.obj) {
                  form.value["user_id"] = list.result.obj.user_id;
                  $post("/api/" + group_table.value + "/add", form.value).then((res) => {
                        console.log("提交结果：", res);
                        if (res.result) {
						  storageHelper.setUserInfo(form_user.value)
                          ElMessage.success("添加成功");
                          ruleFormRef.value.resetFields();
                          router.push("./table");
                        } else if (res.error) {
                          var user_id = form.value["user_id"];
                                $get("/api/user/del", { user_id });
                          ElMessage.error(res.error.message);
                        }
                      }
                  );
                }
              });
            } else if (res.error) {
              ElMessage.error(res.error.message);
            }
          });
        }
      } else {
        ElMessage.error(msg);
      }
    };
    // 提交前校验
    let submit_check_user = async (param) => {
      var ret = null;

      var email_regular = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

      var { username, password, nickname, user_group, email } = param;

      if (!username) {
        ret = "账号不能为空";
      } else if (username.length > 16 || username.length < 5) {
        ret = "账号长度应为5到16个字符之间！";
      } else if (!password) {
        ret = "密码不能为空!";
      } else if (
          is_password.value &&
          (password.length > 16 || password.length < 5)
      ) {
        ret = "密码长度应为5到16个字符之间！";
      } else if ((nickname && nickname.length > 12) || nickname.length < 2) {
        ret = "昵称长度应为2个字符到12个字符之间";
      } else if (email && !email_regular.test(email)) {
        ret = "请输入正确的邮箱地址 例：test@test.com!";
      }

      else if (!user_group) {
        ret = "请选择用户组!";
      }

      var p = { username: param.username };

      var form_obj = Object.assign({}, form.value);
                                                                                                  let store_phone_phone_regular = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if(form_obj.store_phone && !store_phone_phone_regular.test(form_obj.store_phone)){
        return "手机号格式错误"
      }
                                                                                                                                        
      return ret;
    };
    // 提交成功后
    let submit_after = (json, func) => {
      var formObj = Object.assign({}, form_user.value);
      delete formObj.password;
      console.log("查询表单form", formObj);
      get_register(formObj);
    };
    // 获取注册表信息
    let get_register = (form) => {
        $get("/api/user/get_obj", form).then((res) => {
        console.log("注册表信息res", res);
        if (res.result && res.result.obj) {
          form.value.user_id = res.result.obj.user_id;
          submit_sub(form.value);
        } else if (res.error) {
          console.error(res.error);
          ElMessage.error(res.error.message);
        }
      });
    };
    // 提交附加信息
    let submit_sub = (form_sub) => {
      if (form_sub["registered_users_id"]) {
        // 提交事件
        delete form_sub.update_time;
        $post("/api/" + group_table.value + "/set?merchant_users_id=" + form_sub["merchant_users_id"],form_sub
        ).then((res) => {
          console.log("提交结果：", res);
          if (res.result) {
            ElMessage.success("修改成功");
            router.go(-2);
          } else if (res.error) {
            console.error(res.error);
            ElMessage.error("上传失败！");
          }
        });
      } else {
        // 提交事件
          $post("/api/" + group_table.value + "/add", form_sub).then((res) => {
          console.log("提交结果：", res);
          if (res.result) {
            ElMessage.success("添加成功");
            router.go(-2);
          } else if (res.error) {
            var user_id = form_sub["user_id"];
            $get("/api/user/del", { user_id });
            ElMessage.error(res.error.message);
          }
        });
      }
    };
  // 查询数组对象某个是否包含某个值,返回对应对象
  let getObj = (arr, val) => {
    let obj = arr.find((item) => item.user_id == val);
    let ret = "";
    if (obj) {
      if (obj.nickname) {
        ret = obj.nickname;
      } else {
        ret = obj.username;
      }
    }
    return ret;
  };
  //获取对象之前
  let get_obj_before = (param) => {
    var formArr = "";
                                  if(form.value && formArr){
      Object.keys(form.value).forEach(key => {
        Object.keys(formArr).forEach(dbKey => {
          if(key === dbKey){
            disabledObj.value[key+'_isDisabled'] = true;
          }
        })
      })
    }
                            localStorage.removeItem('form')
    return param;
  }
  // js判断字段是否是时间戳格式
  let isTimestamp = (value) => {
    return /^\d{10}$/.test(value) || /^\d{13}$/.test(value);
  }
  //获取对象之后
  let get_obj_after = (json, func) => {
    if (json) {
      var user = json.result.obj;
      is_password.value = user.password ? false : true;
      var user_id = user.user_id;
            $get("/api/" + group_table.value + "/get_obj", {user_id}).then((res) => {
        if (res.result && res.result.obj) {
          var o = res.result.obj;
          delete o["create_time"];
          delete o["update_time"];
          form.value = res.result.obj;
                                                                                                                                                                                        } else if (res.error) {
          console.log(res.error);
          console.log("获取不到相关信息");
        }
      });
    }
  }
  let is_view = () => {
    var bl = user_group == "管理员";
    if (!bl) {
      bl = $check_action('/merchant_users/table', 'add');
      console.log(bl ? "你有表格添加权限视作有添加权限" : "你没有表格添加权限");
    }
    if (!bl) {
      bl = $check_action('/merchant_users/table', 'set');
      console.log(bl ? "你有表格添加权限视作有修改权限" : "你没有表格修改权限");
    }
    if (!bl) {
      bl = $check_action('/merchant_users/view', 'add');
      console.log(bl ? "你有视图添加权限视作有添加权限" : "你没有视图添加权限");
    }
    if (!bl) {
      bl = $check_action('/merchant_users/view', 'set');
      console.log(bl ? "你有视图修改权限视作有修改权限" : "你没有视图修改权限");
    }
    if (!bl) {
      bl = $check_action('/merchant_users/view', 'get');
      console.log(bl ? "你有视图查询权限视作有查询权限" : "你没有视图查询权限");
    }
    console.log(bl ? "具有当前页面的查看权，请注意这不代表你有字段的查看权" : "无权查看当前页，请注意即便有字段查询权限没有页面查询权限也不行");
    return bl;
  }
  // 获取详情
  let get_merchant_users_obj = async () => {
    let query_user_id = route.query.user_id
    let list = await $get("/api/user/get_obj?user_id=" + query_user_id);
    get_obj_before(form_user.value);
    get_obj_after(list);
    form_user.value = list.result.obj;
    obj_user.value = form_user.value;
  };
  onMounted(() => {
                            let query_user_id = route.query.user_id
    if (query_user_id) {
      get_merchant_users_obj();
    }else {
      get_obj_before();
      get_obj_after();
    }

  });
</script>

<style scoped lang="less">
  .diy_edit {
    width: 100%;

    .edit_merchant_users_form {
      max-width: 80%;
      margin: 90px auto;

      .fn {
        width: 100%;
      }
    }

    img {
      width: 100px;
      height: 100px;
    }

    .edit_list_merchant_users_sell {
      width: 80%;
      margin: 90px auto;
    }

    .footer {
      text-align: center;
    }
  }
</style>
  